package com.steellee.leeexcel;

import com.steellee.leeexcel.abstruct.PaOwnCheckMapExtend;
import com.steellee.leeexcel.dto.MetaExcelReadDTO;
import com.steellee.leeexcel.dto.MetaSheetInfo;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OwnMapCheck extends PaOwnCheckMapExtend {
    @Override
    @SneakyThrows
    public Map<String, String> ownCheckStart(String errMsg, String errIndex, Map<Integer
            , List<Map<Object, Object>>> dataLists, List<MetaSheetInfo> metaSheet, List<MetaExcelReadDTO> param) {
        Map<String, String> result = new HashMap<>();
        StringBuffer msg = new StringBuffer(errMsg);
        StringBuffer index = new StringBuffer(errIndex);
        // sheet0
        List<Map<Object, Object>> dataList = dataLists.get("0");
        for (int i = 0; i < dataList.size(); i++) {
            Map<Object, Object> dto = dataList.get(i);
            if (!"二级制度".equals(dto.get("cc").toString())) {
                addMsg(msg, index, "cc", metaSheet.get(0), i, param.get(0).getHeads());
            }
        }
        // sheet1
        dataList = dataLists.get("1");
        for (int i = 0; i < dataList.size(); i++) {
            Map<Object, Object> dto = dataList.get(i);
            if (!"二级制度".equals(dto.get("cc").toString())) {
                addMsg(msg, index, "cc", metaSheet.get(1), i, param.get(0).getHeads());
            }
        }

        if (!StringUtils.isEmpty(msg.toString()) && !StringUtils.isEmpty(index.toString())) {
            result.put("errMsg", msg.toString());
            result.put("errIndex", index.toString());
        }
        return result;
    }


    private void addMsg(StringBuffer errMsg, StringBuffer errIndex, String fieldName, MetaSheetInfo metaSheet, int num, String[] head) throws Exception {
        List<String> heads = Arrays.asList(head);
        if (heads.contains(fieldName)) {
            String errInfo = "sheet:\"" + metaSheet.getSheetName() +
                    "\"第" + (num + 2) + "行:" + fieldName;
            if (!StringUtils.isEmpty(errMsg.toString())) {
                errMsg.append(",");
            }
            errMsg.append(errInfo);
            if (!StringUtils.isEmpty(errIndex.toString())) {
                errIndex.append(";");
            }
            errIndex.append(metaSheet.getSheetNo() + "," + (num + 1) + "," + heads.indexOf(fieldName));
        }
    }
}